package com.chainyoung.trademarket.mvp.presenter;

import com.chainyoung.common.appcommon.entity.CommonList;
import com.chainyoung.common.base.CommonSubscriber;
import com.chainyoung.common.constant.LibConstant;
import com.chainyoung.common.di.scope.FragmentScope;
import com.chainyoung.common.exception.ApiException;
import com.chainyoung.common.mvp.BasePresenter;
import com.chainyoung.common.utils.RxUtils;
import com.chainyoung.trademarket.entity.Msg;
import com.chainyoung.trademarket.entity.MsgNum;
import com.chainyoung.trademarket.mvp.contract.MsgCenterContract;
import com.chainyoung.trademarket.mvp.contract.MsgFragmentContract;

import java.util.List;
import java.util.TreeMap;

import javax.inject.Inject;


@FragmentScope
public class MsgFragmentPresenter extends BasePresenter<MsgFragmentContract.Model, MsgFragmentContract.View> {

    @Inject
    public MsgFragmentPresenter(MsgFragmentContract.Model model, MsgFragmentContract.View rootView) {
        super(model, rootView);
    }


    public void updateMsgStatus(TreeMap<String, Object> map) {

        addSubscribe(mModel.updateMsgStatus(map)
                .compose(RxUtils.<MsgNum>rxSchedulerHelper())
                .subscribeWith(new CommonSubscriber<MsgNum>(mView,true) {
                    @Override
                    public void onNext(MsgNum data) {
                        mView.onUpdateMsgStatus(data);
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }
                }));
    }


    public void getMsgList(TreeMap<String, Object> map) {
        addSubscribe(mModel.getMsgList(map)
                .compose(RxUtils.<List<CommonList<Msg>>>rxSchedulerHelper())
                .subscribeWith(new CommonSubscriber<List<CommonList<Msg>>>(mView) {
                    @Override
                    public void onNext(List<CommonList<Msg>> data) {
                        mView.onGetMsgList(data);
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (e instanceof ApiException) {
                            if (((ApiException) e).getErrorCode().endsWith(LibConstant.NO_RESULT_ERRORCODE)) {
                                mView.onGetMsgList(null);
                                return;
                            }
                        }
                        mView.onGetMsgFailed();
                        super.onError(e);
                    }
                }));
    }
}
